package com.nptever.webcamera.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author ZhangKai
 * @version 1.0
 * @decription SOAP 工具类， 负责SOAP XML与JAVA对象互转，以及WebService服务相关工具
 * @date 2018/11/16 16:15
 */
public class SoapUtil {

    private static final Logger logger = LoggerFactory.getLogger(SoapUtil.class);

    private static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * pojo转换成xml 默认编码UTF-8
     */
    public static String convertBeanToXml(Object obj) throws Exception {
        return convertBeanToXml(obj, DEFAULT_ENCODING);
    }

    /**
     * pojo转换成xml
     */
    public static String convertBeanToXml(Object obj, String encoding) throws Exception {
        String result;
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        // 生成报文的格式化
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();
        return result;
    }
    /**
     * xml转换成pojo
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertXmlToJavaBean(String xml, Class<T> t) throws Exception {
        T obj;
        JAXBContext context = JAXBContext.newInstance(t);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        obj = (T) unmarshaller.unmarshal(new StringReader(xml));
        return obj;
    }

    /**
     * 发送WS请求
     * @param url Webservice URL 地址
     * @param xmlString Soap Body XML字符串
     * @return 响应结果XML字符串
     * @throws Exception
     */
    public static String send(String url, String xmlString) throws Exception{

        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/xml");
        httpPost.setHeader("Content-Type", "application/xml");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(xmlString, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{
                logger.error("请求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
